<template>
  <div class="diagnosis-container" :key="queryParams.scope">
    <!-- 查询与操作区域 -->
    <div class="search-box">
      <div class="search-box-left">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="0">
          <el-form-item>
            <!-- 住院范围选择：本次住院 / 全部住院 -->
            <el-select v-model="queryParams.scope" placeholder="请选择住院范围" @change="handleQuery">
              <el-option v-for="opt in scopeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="search-box-right">
        <el-button class="add-btn op-btn" type="primary" @click="openAddDiagnosis">下诊断</el-button>
      </div>
    </div>

    <!-- 诊断列表区域 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="diagnosisList" size="default" @row-click="openDetail">
        <el-table-column type="index" width="55" align="center" />
        <el-table-column label="诊断类型" prop="type" align="center" width="120" />
        <el-table-column label="诊断" prop="name" align="left" min-width="220" show-overflow-tooltip />
        <el-table-column label="ICD" prop="icd" align="center" width="120">
          <template #default="scope">
            <!-- 展示分类标签：主/西医等，示例占位 -->
            <span class="icd-cat">[主][西医]</span>
            {{ scope.row.icd || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="发病日期" prop="onsetDate" align="center" width="120" />
        <el-table-column label="诊断日期" prop="diagnosisDate" align="center" width="120" />
        <el-table-column label="诊断医生" prop="doctorName" align="center" width="120" />
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="queryParams-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 下诊断弹窗（重构为独立组件） -->
    <DiagnosisDialog
      v-model:visible="addDialogVisible"
      :patient="currentPatient"
      :historyList="diagnosisList"
      :currentUserName="currentUserName"
      @save="handleDialogSave"
    />
  </div>
</template>

<script setup name="Diagnosis">
// 使用 Vue3 Composition API，JavaScript 语法
import { ref, reactive, onMounted } from 'vue'
import DiagnosisDialog from './components/DiagnosisDialog.vue'
import { getDiagnosesList } from '@/api/residentDoctor/clinicalRecords'

const props = defineProps({
  patient: {
    type: Object,
    default: () => ({})
  }
})

watch(
  () => props.patient,
  patient => {
    if (patient && patient.patientId) {
      currentPatient = { ...patient }
      currentPatient.age = calculateAge(patient.birthDate)
    }
  }
)

// 计算年龄
const calculateAge = birthDate => {
  if (!birthDate) return ''
  const birth = new Date(birthDate)
  if (isNaN(birth)) return ''
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const month = today.getMonth() - birth.getMonth()
  const day = today.getDate() - birth.getDate()
  if (month < 0 || (month === 0 && day < 0)) {
    age--
  }
  return `${age}`
}

// 查询参数：范围、本页码、分页大小
const queryParams = reactive({
  scope: 'all', // all: 全部住院；current: 本次住院
  pageNum: 1,
  pageSize: 10
})

// 住院范围选项
const scopeOptions = [
  { label: '全部住院', value: 'all' },
  { label: '本次住院', value: 'current' }
]

// 列表数据与状态
const loading = ref(false)
const total = ref(0)
const diagnosisList = ref([])

// 下诊断弹窗相关
const addDialogVisible = ref(false)
let currentPatient = reactive({})
const currentUserName = '李星云'

function openAddDiagnosis() {
  addDialogVisible.value = true
}

// 接收弹窗保存数据，合入列表并做用户反馈
function handleDialogSave(rows) {
  getDiagnosesList()
  addDialogVisible.value = false
}

// 行点击（预留：打开详细信息或编辑）
function openDetail(row) {
  // 预留：可打开诊断详情抽屉/弹窗
  // console.log('诊断详情：', row)
}

// 查询与分页
function handleQuery() {
  queryParams.pageNum = 1
  fetchDiagnosisList()
}

function handlePageChange(page) {
  queryParams.pageNum = page
  fetchDiagnosisList()
}

// 拉取数据
async function fetchDiagnosisList() {
  loading.value = true
  try {
    const { data, total: t } = await getDiagnosesList(queryParams)
    diagnosisList.value = data || []
    total.value = t
  } finally {
    loading.value = false
  }
}

// 页面挂载后默认拉取一次
onMounted(() => {
  fetchDiagnosisList()
})
</script>

<style scoped lang="scss">
@use '@/assets/styles/variables.module.scss' as *;

.diagnosis-container {
  padding: 0 $padding-md;
}

.search-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $margin-md;
}
.search-box-left {
  display: flex;
  align-items: center;
}
.search-box-right {
  display: flex;
  align-items: center;
  .op-btn {
    min-width: 96px;
  }
}

.table-container {
  background: #fff;
  border-radius: $border-radius;
  box-shadow: 0 1px 3px $box-shadow-color;
  padding: $padding-sm;
}

.queryParams-container {
  display: flex;
  justify-content: flex-end;
  padding: $padding-sm;
}

.icd-cat {
  color: $sub-font-color;
  margin-right: $margin-sm;
}

/* 响应式适配：窄屏下搜索区域纵向排列 */
@media (max-width: 768px) {
  .search-box {
    flex-direction: column;
    align-items: stretch;
    gap: $margin-sm;
  }
  .search-box-right {
    justify-content: flex-end;
  }
}
</style>
